/*
 * @Description: Description
 * @Autor: Chen
 * @Date: 2020-08-26 11:13:00
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-05-25 09:18:03
 */
import { Injectable } from '@angular/core';
import {
  CanActivate, CanActivateChild, CanDeactivate, CanLoad, Route,
  UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router
} from '@angular/router';
import { Observable } from 'rxjs';
import { StorageService } from '../services/storage.service';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanActivateChild, CanDeactivate<unknown>, CanLoad {
  constructor(
    private authService: AuthService,
    private router: Router,
    private stoageServe: StorageService,
  ) { }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.checkLogin(state.url);
  }
  canActivateChild(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return true;
  }
  canDeactivate(
    component: unknown,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return true;
  }
  canLoad(
    route: Route,
    segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
    return true;
  }
  checkLogin(url: string): boolean {
    this.authService.redirectUrl = url;
    const token = this.stoageServe.getStorage('token');
    if (token) {
      this.authService.token = token;
      const ucUserInfo = this.stoageServe.getStorage('ucUserInfo');
      const cardNoOfData = this.stoageServe.getStorage('cardNoOfData');
      if (ucUserInfo) {
        this.authService.userInfo = JSON.parse(ucUserInfo);
      }
      if (cardNoOfData) {
        this.authService.cardNoOfData = JSON.parse(cardNoOfData);
      }
      return true;
    } else {
      return false;
    }
  }
}
